/**
 * 接口加密工具
 * 
 * @author ruoyi
 */
(function(window) {
    // 默认密钥和偏移量，需要与后端保持一致
    const DEFAULT_KEY = "aW0t5adf1uNdP7jU";
    const DEFAULT_IV = "RbmhNetworkRuoYi";
    
    // AES加密
    function encrypt(data, key, iv) {
        key = key || DEFAULT_KEY;
        iv = iv || DEFAULT_IV;
        
        // 处理密钥和偏移量
        var keyWordArray = paddingKey(key);
        var ivWordArray = paddingKey(iv);
        
        // 加密
        var encrypted = CryptoJS.AES.encrypt(data, keyWordArray, {
            iv: ivWordArray,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        
        return encrypted.toString();
    }
    
    // AES解密
    function decrypt(data, key, iv) {
        key = key || DEFAULT_KEY;
        iv = iv || DEFAULT_IV;
        
        try {
            // 处理密钥和偏移量，与后端保持一致
            var keyWordArray = paddingKey(key);
            var ivWordArray = paddingKey(iv);
            
            // 解密
            var decrypted = CryptoJS.AES.decrypt(data, keyWordArray, {
                iv: ivWordArray,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            
            // 转换为UTF-8字符串
            var decryptedStr = decrypted.toString(CryptoJS.enc.Utf8);
            
            return decryptedStr;
        } catch (e) {
            console.error('解密过程发生异常:', e);
            return null;
        }
    }
    
    // 密钥填充或截断为16字节，与后端System.arraycopy逻辑完全一致
    function paddingKey(key) {
        // 1. 使用CryptoJS获取密钥的UTF-8字节，与后端key.getBytes(StandardCharsets.UTF_8)保持一致
        var keyWordArray = CryptoJS.enc.Utf8.parse(key);
        
        // 2. 将WordArray转换为字节数组
        var keyBytes = [];
        var words = keyWordArray.words;
        var sigBytes = keyWordArray.sigBytes;
        
        for (var i = 0; i < sigBytes; i++) {
            var byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
            keyBytes.push(byte);
        }
        
        // 3. 创建16字节的结果数组，初始化为0
        var result = new Array(16);
        for (var i = 0; i < 16; i++) {
            result[i] = 0;
        }
        
        // 4. 复制密钥字节，与后端System.arraycopy逻辑一致
        var copyLength = Math.min(keyBytes.length, 16);
        for (var i = 0; i < copyLength; i++) {
            result[i] = keyBytes[i];
        }
        
        // 5. 转换为CryptoJS的WordArray
        var words = [];
        for (var i = 0; i < 16; i += 4) {
            words.push((result[i] << 24) | (result[i+1] << 16) | (result[i+2] << 8) | result[i+3]);
        }
        
        return CryptoJS.lib.WordArray.create(words, 16);
    }
    
    // 暴露API
    window.ApiEncrypt = {
        encrypt: encrypt,
        decrypt: decrypt
    };
})(window);